package com.colter.project.sample.jedis;

import java.util.ArrayList;
import java.util.List;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPool;

public class JedisClient {
	private String ip = "localhost";
	private Jedis jedis;
	private JedisPool jedisPool;
	private ShardedJedis sharedJedis;
	private ShardedJedisPool shardedJedisPool;

	public Jedis getJedis() {
		return jedis;
	}

	public void setJedis(Jedis jedis) {
		this.jedis = jedis;
	}

	public ShardedJedis getSharedJedis() {
		return sharedJedis;
	}

	public void setSharedJedis(ShardedJedis sharedJedis) {
		this.sharedJedis = sharedJedis;
	}

	public JedisClient() {
		initPool();
		initSharedPool();
		sharedJedis = shardedJedisPool.getResource();
		jedis = jedisPool.getResource();
	}

	private void initPool() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(5);
		config.setMaxWaitMillis(10000);
		config.setMaxTotal(20);
		config.setTestOnBorrow(false);
		jedisPool = new JedisPool(config, ip , 6379);
	}

	/**
	 * 初始化切片池
	 */
	private void initSharedPool() {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxIdle(5);
		config.setMaxWaitMillis(10000);
		config.setMaxTotal(20);
		config.setTestOnBorrow(false);
		// slave链接
		List<JedisShardInfo> shards = new ArrayList<JedisShardInfo>();
		shards.add(new JedisShardInfo(ip, 6379, "master"));

		// 构造池
		shardedJedisPool = new ShardedJedisPool(config, shards);
	}

	protected void closeResource() {
		try {
			if (!jedisPool.isClosed()) {
				jedisPool.close();
			}
		} catch (Exception e) {
			destroyJedis(jedis);
		}

	}

	public static void destroyJedis(Jedis jedis) {
		if ((jedis != null) && jedis.isConnected()) {
			try {
				try {
					jedis.quit();
				} catch (Exception e) {
				}
				jedis.disconnect();
			} catch (Exception e) {
			}
		}
	}
}
